/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package do_.com.bpd.business.referrals.persistence.controllers;

import do_.com.bpd.business.referrals.persistence.Utils;
import do_.com.bpd.business.referrals.persistence.entities.Referral;
import do_.com.bpd.business.referrals.persistence.exceptions.NonexistentEntityException;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.FlushModeType;
import javax.persistence.Persistence;
import javax.persistence.QueryHint;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.eclipse.persistence.config.CacheUsage;
import org.eclipse.persistence.config.QueryHints;

/**
 *
 * @author Administrator
 */
public class ReferralJpaController implements Serializable {

    public ReferralJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }

    public ReferralJpaController() {
        this.emf = Persistence.createEntityManagerFactory(Utils.PERSISTENCE_UNIT_NAME);
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public List findEntitiesForField(String name, String field, String fieldValue, String comparison) {
        EntityManager em = null;
        if ((name != null) && (!name.isEmpty())) {
            try {
                em = getEntityManager();
//                System.out.println("name:" + name);
                //Query qw = em.createQuery("SELECT l FROM " + name + " l WHERE l.id = :id and l.status <> :status");
                String query = "SELECT l FROM " + name + " l WHERE l." + field + " " + comparison + " :" + field;
                Query qw = em.createQuery(query);
                qw.setParameter(field, fieldValue);
//                qw.setParameter("status", "Removed");
                List list = qw.getResultList();
//                if (list != null && list.size() > 0) {
//                    return list.get(0);
//                }
                return list;
            } finally {
                if (em != null) {
                    em.close();
                }
            }
        }
        return null;
    }

    public void create(Referral referral) {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            em.persist(referral);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Referral referral) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            referral = em.merge(referral);
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = referral.getId();
                if (findReferral(id) == null) {
                    throw new NonexistentEntityException("The referral with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Referral referral;
            try {
                referral = em.getReference(Referral.class, id);
                referral.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The referral with id " + id + " no longer exists.", enfe);
            }
            em.remove(referral);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    private boolean checkParam(String param) {
        if (param != null && !param.isEmpty()) {
            return true;
        }
        return false;
    }

    private String getFilterType(String filterType) {
        if (checkParam(filterType)) {
            if (filterType.equalsIgnoreCase("1")) {
                return "trackId";
            } else if (filterType.equalsIgnoreCase("2")) {
                return "referrerId";
            } else if (filterType.equalsIgnoreCase("3")) {
                return "productNumber";
            } else if (filterType.equalsIgnoreCase("4")) {
                return "customerName";
            }
        }

        return null;
    }

    public List<Referral> findReferralEntitiesByFilter(String keyword, String filterType, String dateSince, String dateUntil) {
        EntityManager em = null;
        List<Referral> results=new ArrayList<Referral>();
        try {
            em = getEntityManager();
            String query = "SELECT x FROM Referral x ";
            String queryWhere = "";
            boolean whereActivated = false;
            boolean andActivated = false;

            String fieldFilterType = getFilterType(filterType);

            ///unificar el query
            //1: add field for filter
            //queryWhere += "x."+fieldFilterType + "='" + keyword+"'";
            //System.out.println("Filet++"+fieldFilterType);
            if (fieldFilterType != null && keyword != null) {
                if (!whereActivated) {
                    queryWhere = "WHERE ";
                    whereActivated = true;
                }

                queryWhere += "x." + fieldFilterType + " like '%" + keyword + "%'";
                andActivated = true;
            }
            //2: add date since
            if (checkParam(dateSince)) {

                if (andActivated) {
                    queryWhere += " and ";
                } else {
                    if (!whereActivated) {
                        queryWhere = "WHERE ";
                        whereActivated = true;
                    }
                }
                andActivated = true;
                queryWhere += "x.referralDate >='" + dateSince + "'";
            }
            //3: add date until
            if (checkParam(dateUntil)) {
                if (andActivated) {
                    queryWhere += " and ";
                } else {
                    if (!whereActivated) {
                        queryWhere = "WHERE ";
                        whereActivated = true;
                    }
                }
                andActivated = true;
                queryWhere += "x.referralDate <='" + dateUntil + "'";
            }
            query += queryWhere;
            System.out.println("Query:" + query);
            Query q = em.createQuery(query);
            results = q.getResultList();
        } finally {
            if (em != null) {
                em.close();
            }
        }
        return results;
    }

    public static String getDateStringFromDate(Date date, String format) {
        SimpleDateFormat formatoDeFecha = new SimpleDateFormat(format);
        return formatoDeFecha.format(date);
    }

    public static Date getDateFromString(String date, String format) {
        Date fecha = null;
        try {
            SimpleDateFormat formatoDelTexto = new SimpleDateFormat(format);
            fecha = formatoDelTexto.parse(date);
        } catch (ParseException ex) {
            System.out.println("Error");
        }
        return fecha;
    }

    public List<Referral> findReferralEntities() {
        return findReferralEntities(true, -1, -1);
    }

    public List<Referral> findReferralEntities(int maxResults, int firstResult) {
        return findReferralEntities(false, maxResults, firstResult);
    }

    private List<Referral> findReferralEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = null;
        try {
            em = getEntityManager();
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Referral.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            if(em!=null)
            em.close();
        }
    }

    public Referral findReferral(Integer id) {
        EntityManager em = null;
        try {
            em = getEntityManager();
            Referral find = em.find(Referral.class, id);
            System.out.println("Referral is " + find);
            emf.getCache().evict(Referral.class);
            return find;
        } finally {
            if(em!=null)
            em.close();
        }
    }

    public int getReferralCount() {
        EntityManager em = null;
        try {
            em = getEntityManager();
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Referral> rt = cq.from(Referral.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            if(em!=null)
            em.close();
        }
    }
        public void closeEntityManagerFactory() {
        if (emf != null) {
            emf.close();
        }
    }
}
